package lzy.controller;

import lzy.entity.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import lzy.service.GinsengService;
import lzy.service.QualityInspectionService;
import lzy.service.ProcessingEquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import lzy.service.BatchService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import lzy.service.PackagingService;
import lzy.service.WarehousingService;
import lzy.service.LogisticsService;
import lzy.service.SalesService;

@RequestMapping("/processing")
@Controller
public class ProcessingController {

    @Autowired
    private GinsengService ginsengService;
    @Autowired
    private QualityInspectionService qualityInspectionService;
    @Autowired
    private ProcessingEquipmentService processingEquipmentService;
    @Autowired
    private BatchService batchService;
    @Autowired
    private lzy.service.PackagingService packagingService;
    @Autowired
    private lzy.service.WarehousingService warehousingService;
    @Autowired
    private lzy.service.LogisticsService logisticsService;
    @Autowired
    private lzy.service.SalesService salesService;

    @GetMapping("/dashboard")
    public String processingDashboard(HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PROCESSING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }
        return "dashboard_pc";
    }

    @GetMapping("/quality_control")
    public String qualityControl(
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) String inspectType,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        //============        登录拦截        ================
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PROCESSING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }

        model.addAttribute("batchList", batchService.findAll());
        java.util.List<String> inspectTypeList = java.util.Arrays.asList("初质检", "二次质检");
        model.addAttribute("inspectTypeList", inspectTypeList);
        java.util.List<QualityInspection> qualityChecks = qualityInspectionService.findByFilter(batchNo, inspectType, startTime, endTime);
        model.addAttribute("qualityChecks", qualityChecks);
        // ====== Chart数据JSON输出补全（可保留原有示例数据） ======
        java.util.List<String> passRateLabels = new java.util.ArrayList<>();
        java.util.List<Double> passRateData = new java.util.ArrayList<>();
        java.util.List<String> gradeLabels = new java.util.ArrayList<>();
        java.util.List<Double> gradeData = new java.util.ArrayList<>();
        passRateLabels.add("2024-06-01"); passRateLabels.add("2024-06-02");
        passRateData.add(90.0); passRateData.add(95.0);
        gradeLabels.add("A级"); gradeLabels.add("B级"); gradeLabels.add("C级");
        gradeData.add(10.0); gradeData.add(5.0); gradeData.add(2.0);
        com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
        try {
            model.addAttribute("passRateLabelsJson", mapper.writeValueAsString(passRateLabels));
            model.addAttribute("passRateDataJson", mapper.writeValueAsString(passRateData));
            model.addAttribute("gradeLabelsJson", mapper.writeValueAsString(gradeLabels));
            model.addAttribute("gradeDataJson", mapper.writeValueAsString(gradeData));
        } catch (Exception e) {
            model.addAttribute("passRateLabelsJson", "[]");
            model.addAttribute("passRateDataJson", "[]");
            model.addAttribute("gradeLabelsJson", "[]");
            model.addAttribute("gradeDataJson", "[]");
        }
        // 统计本月质检数（近30天）
        int monthlyChecks = qualityInspectionService.countInLastDays(30);
        model.addAttribute("monthlyChecks", monthlyChecks);
        // 统计合格率
        int total = qualityInspectionService.countAll();
        int passed = qualityInspectionService.countByResult("通过");
        String passRate = total > 0 ? String.format("%.1f", passed * 100.0 / total) : "0";
        model.addAttribute("passRate", passRate);
        return "processing/quality_control";
    }

    @GetMapping("/equipment_management")
    public String equipmentManagement(HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        User user = (User) session.getAttribute("user");
        //============        登录拦截        ================
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PROCESSING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }

        java.util.List<lzy.entity.ProcessingEquipment> equipmentList = processingEquipmentService.findAll();
        model.addAttribute("equipmentList", equipmentList);

        // ====== 自动统计设备状态和类型数据，并转为JSON字符串 ======
        java.util.Map<String, Integer> statusMap = new java.util.HashMap<>();
        java.util.Map<String, Integer> typeMap = new java.util.HashMap<>();
        for (lzy.entity.ProcessingEquipment eq : equipmentList) {
            // 统计状态（将Integer转为String作为key）
            String status = eq.getStatus() == null ? "未知" : eq.getStatus().toString();
            statusMap.put(status, statusMap.getOrDefault(status, 0) + 1);
            // 统计类型（equipName为String）
            String type = eq.getEquipName() == null ? "未知" : eq.getEquipName();
            typeMap.put(type, typeMap.getOrDefault(type, 0) + 1);
        }
        java.util.List<String> statusLabels = new java.util.ArrayList<>(statusMap.keySet());
        java.util.List<Integer> statusData = new java.util.ArrayList<>();
        for (String key : statusLabels) statusData.add(statusMap.get(key));
        java.util.List<String> typeLabels = new java.util.ArrayList<>(typeMap.keySet());
        java.util.List<Integer> typeData = new java.util.ArrayList<>();
        for (String key : typeLabels) typeData.add(typeMap.get(key));
        com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
        try {
            model.addAttribute("statusLabelsJson", mapper.writeValueAsString(statusLabels));
            model.addAttribute("statusDataJson", mapper.writeValueAsString(statusData));
            model.addAttribute("typeLabelsJson", mapper.writeValueAsString(typeLabels));
            model.addAttribute("typeDataJson", mapper.writeValueAsString(typeData));
        } catch (Exception e) {
            model.addAttribute("statusLabelsJson", "[]");
            model.addAttribute("statusDataJson", "[]");
            model.addAttribute("typeLabelsJson", "[]");
            model.addAttribute("typeDataJson", "[]");
        }
        // 以上均为设备参数统计
        return "processing/equipment_management";
    }

    @GetMapping("/batch_management")
    public String batchManagement(HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PROCESSING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }
        java.util.List<lzy.entity.Batch> batchList = batchService.findAll();
        model.addAttribute("batchList", batchList);

        int todayInCount = batchService.sumInitParamCountToday();
        int weekChecked = batchService.countBatchCheckedIn7Days();
        int checked = batchService.countAllChecked();
        int total = batchService.countAll();
        double completionRate = total > 0 ? (checked * 100.0 / total) : 0.0;
        model.addAttribute("todayInCount", todayInCount);
        model.addAttribute("weekChecked", weekChecked);
        model.addAttribute("completionRate", String.format("%.1f", completionRate));
        
        return "processing/batch_management";
    }

    @PostMapping("/updateBatch")
    @ResponseBody
    public String updateBatch(@RequestBody lzy.entity.Batch batch) {
        batchService.update(batch);
        return "success";
    }

    @PostMapping("/addBatch")
    @ResponseBody
    public String addBatch(@RequestBody java.util.Map<String, Object> payload) {
        lzy.entity.Batch batch = new lzy.entity.Batch();
        batch.setBatchNo((String) payload.get("batchNo"));
        batch.setSourceBaseId(Long.valueOf(payload.get("sourceBaseId").toString()));
        batch.setInitParamCount(Integer.valueOf(payload.get("initParamCount").toString()));
        batch.setCheck1("未质检");
        batch.setCheck2("未质检");
        batch.setCreateDate(new java.util.Date());
        batchService.save(batch);
        return "success";
    }

    @PostMapping("/updateEquipmentParams")
    @ResponseBody
    public String updateEquipmentParams(@RequestBody java.util.Map<String, Object> payload) {
        Integer equipId = Integer.valueOf(payload.get("equipId").toString());
        String params = (String) payload.get("params");
        lzy.entity.ProcessingEquipment equipment = processingEquipmentService.findById(equipId);
        equipment.setParams(params);
        processingEquipmentService.update(equipment);
        return "success";
    }

    @PostMapping("/addQualityInspection")
    @ResponseBody
    public String addQualityInspection(@RequestBody QualityInspection inspection) {
        qualityInspectionService.insert(inspection);
        return "success";
    }

    @GetMapping("/findQualityInspectionByBatchNo")
    @ResponseBody
    public java.util.List<QualityInspection> findQualityInspectionByBatchNo(String batchNo) {
        return qualityInspectionService.findByBatchNo(batchNo);
    }

    @GetMapping("/packaging_management")
    public String packagingManagement(
            @RequestParam(required = false) String packagingNo,
            @RequestParam(required = false) String packagingType,
            @RequestParam(required = false) String personInCharge,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PROCESSING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        java.util.Date start = null, end = null;
        try { if (startTime != null && !startTime.isEmpty()) start = sdf.parse(startTime); } catch (Exception ignored) {}
        try { if (endTime != null && !endTime.isEmpty()) end = sdf.parse(endTime); } catch (Exception ignored) {}
        java.util.List<lzy.entity.Packaging> packagingList = packagingService.findByFilter(packagingNo, packagingType, personInCharge, start, end);
        model.addAttribute("packagingList", packagingList);
        model.addAttribute("packagingNo", packagingNo);
        model.addAttribute("packagingType", packagingType);
        model.addAttribute("personInCharge", personInCharge);
        model.addAttribute("startTime", startTime);
        model.addAttribute("endTime", endTime);
        return "processing/packaging_management";
    }

    @PostMapping("/addPackaging")
    @ResponseBody
    public String addPackaging(@RequestBody lzy.entity.Packaging packaging) {
        packagingService.addPackaging(packaging);
        return "success";
    }

    @GetMapping("/warehousing_management")
    public String warehousingManagement(
            @RequestParam(required = false) String warehouseNo,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) String location,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PROCESSING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        java.util.Date start = null, end = null;
        try { if (startTime != null && !startTime.isEmpty()) start = sdf.parse(startTime); } catch (Exception ignored) {}
        try { if (endTime != null && !endTime.isEmpty()) end = sdf.parse(endTime); } catch (Exception ignored) {}
        java.util.List<lzy.entity.Warehousing> warehousingList = warehousingService.findByFilter(warehouseNo, batchNo, location, start, end);
        model.addAttribute("warehousingList", warehousingList);
        model.addAttribute("warehouseNo", warehouseNo);
        model.addAttribute("batchNo", batchNo);
        model.addAttribute("location", location);
        model.addAttribute("startTime", startTime);
        model.addAttribute("endTime", endTime);
        // 新增：批次下拉选项（status为NULL）
        java.util.List<String> availableBatchNos = batchService.findBatchNosWithNullStatus();
        model.addAttribute("availableBatchNos", availableBatchNos);
        return "processing/warehousing_management";
    }

    @PostMapping("/addWarehousing")
    @ResponseBody
    public String addWarehousing(@RequestBody lzy.entity.Warehousing warehousing) {
        warehousingService.addWarehousing(warehousing);
        return "success";
    }

    @GetMapping("/logistics_management")
    public String logisticsManagement(
            @RequestParam(required = false) String logisticsNo,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) String destination,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PROCESSING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        java.util.Date start = null, end = null;
        try { if (startTime != null && !startTime.isEmpty()) start = sdf.parse(startTime); } catch (Exception ignored) {}
        try { if (endTime != null && !endTime.isEmpty()) end = sdf.parse(endTime); } catch (Exception ignored) {}
        java.util.List<lzy.entity.Logistics> logisticsList = logisticsService.findByFilter(logisticsNo, batchNo, destination, status, start, end);
        model.addAttribute("logisticsList", logisticsList);
        model.addAttribute("logisticsNo", logisticsNo);
        model.addAttribute("batchNo", batchNo);
        model.addAttribute("destination", destination);
        model.addAttribute("status", status);
        model.addAttribute("startTime", startTime);
        model.addAttribute("endTime", endTime);
        return "processing/logistics_management";
    }

    @PostMapping("/addLogistics")
    @ResponseBody
    public String addLogistics(@RequestBody lzy.entity.Logistics logistics) {
        logisticsService.addLogistics(logistics);
        return "success";
    }

    @GetMapping("/sales_management")
    public String salesManagement(
            @RequestParam(required = false) String salesNo,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) String customerName,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PROCESSING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        java.util.Date start = null, end = null;
        try { if (startTime != null && !startTime.isEmpty()) start = sdf.parse(startTime); } catch (Exception ignored) {}
        try { if (endTime != null && !endTime.isEmpty()) end = sdf.parse(endTime); } catch (Exception ignored) {}
        java.util.List<lzy.entity.Sales> salesList = salesService.findByFilter(salesNo, batchNo, customerName, start, end);
        model.addAttribute("salesList", salesList);
        model.addAttribute("salesNo", salesNo);
        model.addAttribute("batchNo", batchNo);
        model.addAttribute("customerName", customerName);
        model.addAttribute("startTime", startTime);
        model.addAttribute("endTime", endTime);
        return "processing/sales_management";
    }

    @PostMapping("/addSales")
    @ResponseBody
    public String addSales(@RequestBody lzy.entity.Sales sales) {
        salesService.addSales(sales);
        return "success";
    }
} 